<template>
  <div class="edit-page-wrap">
    <Head title="基础信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="edit-form-wrap"
        >
          <el-form-item label="归属运营商" prop="orgId">
            <qc-select
              v-if="!id"
              :value="ruleForm.orgId"
              :remote="true"
              :filterable="true"
              :options="optionsS.org"
              placeholder="请选择归属运营商"
              @change="handleChangeOrg"
            >
            </qc-select>
            <div v-else>{{ ruleForm.orgName || '--' }}</div>
          </el-form-item>
          <el-form-item label="分润方名称" prop="name">
            <el-input
              v-model.trim="ruleForm.name"
              placeholder="请输入分润方名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="联系人" prop="contactsName">
            <el-input
              v-model.trim="ruleForm.contactsName"
              placeholder="请输入联系人"
              maxlength="10"
              clearable
            />
          </el-form-item>
          <el-form-item label="联系方式" prop="contactsTelephone">
            <el-input
              v-model.trim="ruleForm.contactsTelephone"
              placeholder="请输入联系方式"
              maxlength="11"
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>
  
<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';
import Head from '@/components/head/index.vue';
import { selectAllOperatorList } from '@/service/apis/org';
import {
  shareProfitSave,
  shareProfitUpdate,
  shareProfitUpdateGetById,
} from '@/service/apis/financial';
import { IS_PHONE_NUM } from '@/utils/verify';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;
const ruleFormRef = ref<FormInstance>();

let optionsS = reactive({
  org: [] as any,
});

// 获取归属运营商
selectAllOperatorList({}).then((res: any) => {
  if (res) {
    nextTick(() => {
      optionsS.org = [...res.listMap];
    });
  }
});

let ruleForm = reactive({
  id: id,
  contactsName: '',
  name: '',
  orgName: '',
  orgId: undefined as unknown,
  contactsTelephone: '',
});
const rules = reactive<FormRules>({
  orgId: [{ required: true, message: '请选择归属运营商', trigger: 'change' }],
  name: [{ required: true, message: '请输入分润方名称', trigger: 'blur' }],
  contactsName: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contactsTelephone: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    {
      pattern: IS_PHONE_NUM,
      message: '请输入正确的联系方式',
      trigger: 'blur',
    },
  ],
});

const back = () => {
  router.go(-1);
};

const handleChangeOrg = async (e: any) => {
  ruleForm.orgId = e;
};

if (id) {
  shareProfitUpdateGetById(id).then((res: any) => {
    if (res) {
      ruleForm.id = res.id;
      ruleForm.contactsName = res.contactsName;
      ruleForm.name = res.name;
      ruleForm.orgName = res.orgName;
      ruleForm.orgId = res.orgId;
      ruleForm.contactsTelephone = res.contactsTelephone;
    }
  });
}

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value) return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  if (id) {
    ruleForm.id = id;
    shareProfitUpdate(ruleForm).then((res) => {
      console.log('res===', res);
      emit('clear-cache');
      back();
    });
  } else {
    shareProfitSave(ruleForm).then((res) => {
      console.log('res===', res);
      emit('clear-cache');
      back();
    });
  }
};
</script>
